package org.smith.docker.sample.service;

import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class HighCPUService {

    private final ThreadFactory threadFactory = new ThreadFactory() {

        private final AtomicInteger count = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "cpu-test-" + count.getAndAdd(1));
        }
    };

    /**
     * CPU 测试
     */
    public void cpuTest() {

        ExecutorService executorService = Executors.newFixedThreadPool(10, threadFactory);

        // CPU 占用高线程
        executorService.execute(() -> {
            while (true) {
                double a = Math.random() * Math.random();
                System.out.println(a);
            }
        });

        // 3 个空闲线程
        executorService.execute(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(() -> {
            while (true) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(() -> {
            while (true) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
